package com.jky.trial.service.impl;

import com.jky.trial.common.BaseResult;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.Pagination;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.entity.*;
import com.jky.trial.mapper.CategoryMapper;
import com.jky.trial.mapper.ProjectMapper;
import com.jky.trial.mapper.UserMapper;
import com.jky.trial.service.RelationService;
import com.jky.trial.service.UserService;
import com.jky.trial.vo.CategoryVo;
import com.jky.trial.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static Integer SIZE = 1000;
    private final UserMapper recordMapper;
    private final CategoryMapper categoryMapper;
    private final ProjectMapper projectMapper;
    private final RelationService relationService ;

    @Autowired
    UserServiceImpl(RelationService relationService ,
            ProjectMapper projectMapper, UserMapper recordMapper, CategoryMapper categoryMapper) {

        this.relationService = relationService;
        this.projectMapper = projectMapper;
        this.recordMapper = recordMapper;
        this.categoryMapper = categoryMapper;
    }

    @Override
    public ListResult jzMember(Integer id) {
        return new ListResult(true,recordMapper.jzMember(id));
    }

    public User findByUsername(String username) {
        User record = new User();
        record.setUserName(username);
        record.setStatus(DataStatus.LOGIC_EXISTS_STATUS.getVal());
        record.setDeleted(false);
        User managerInfo = this.findOne(record);
        if (managerInfo == null) {
            throw new UnknownAccountException();
        }
        CategoryVo role = new CategoryVo();
        role.setDeleted(false);
        role.setType(DataStatus.CATEGORY_DATA_TYPE_ROLE.getVal());
        role.setRType(DataStatus.RELATION_TYPE_USER_ROLE.getVal());
        role.setRSourceId(managerInfo.getId());
        List<CategoryVo> list = categoryMapper.listByDr(role);
        list.forEach(item -> {
            role.setType(DataStatus.CATEGORY_DATA_TYPE_PERMISSION.getVal());
            role.setRSourceId(item.getId());
            role.setRType(DataStatus.RELATION_TYPE_ROLE_PERMISSION.getVal());
            List<CategoryVo> permissions = categoryMapper.listByDr(role);
            item.setPermissions(permissions);
        });
        managerInfo.setRoles(list);
        return managerInfo;
    }

    @Override
    public User findOne(User record) {
        UserExample recordExample = new UserExample();
        UserExample.Criteria criteria = recordExample.createCriteria();
        if (record.getId() != null) criteria.andIdEqualTo(record.getId());//查询条件
        if (record.getName() != null) criteria.andNameEqualTo(record.getName());
        if (record.getUserName() != null) criteria.andUserNameEqualTo(record.getUserName());
        if (record.getPassword() != null) criteria.andPasswordEqualTo(record.getPassword());
        if (record.getPhone() != null) criteria.andPhoneEqualTo(record.getPhone());
        if (record.getStatus() != null) criteria.andStatusEqualTo(record.getStatus());
        if (record.getDeleted() != null) criteria.andDeletedEqualTo(record.getDeleted());
        List<User> users = recordMapper.selectByExample(recordExample);
        User user = null;
        if (users != null && users.size() != 0) {
            user = users.get(0);
            Category dep = categoryMapper.selectByPrimaryKey(user.getDepId());
            user.setBusId(dep.getPId());//业务板块
            this.update(user);
        }
        return user;
    }

    @Override
    public BaseResult create(User record) {
        UserExample user = new UserExample();
        UserExample.Criteria ca = user.createCriteria();
        ca.andDeletedEqualTo(false);
        ca.andUserNameEqualTo(record.getUserName());
        int lst = (int) recordMapper.countByExample(user);
        if (lst > 1) return new BaseResult(false, "登录账号已存在");

        UserExample user1 = new UserExample();
        UserExample.Criteria ca1 = user1.createCriteria();
        ca1.andDeletedEqualTo(false);
        ca1.andPhoneEqualTo(record.getPhone());
        int lst1 = (int) recordMapper.countByExample(user1);
        if (lst1 > 0) return new BaseResult(false, "手机号已存在");

        if (record.getBusId() == null) {
            Category dep = categoryMapper.selectByPrimaryKey(record.getDepId());
            record.setBusId(dep.getPId());//业务板块
        }
        record.setCreateAt(new Date());
        return new BaseResult(true, recordMapper.insertSelective(record));
    }

    @Override
    public int update(User record) {
        return recordMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public BaseResult updatePwd(User record) {
        User user = new User();
        user.setId(record.getId());
        user.setPassword(record.getPassword());
        return new BaseResult(true, recordMapper.updateByPrimaryKeySelective(user));
    }

    @Transactional
    @Override
    public BaseResult del(int id) {
        User user = new User();
        user.setId(id);
        user.setDeleted(true);
        ProjectExample projectExample = new ProjectExample();
        ProjectExample.Criteria ca = projectExample.createCriteria();
        ca.andDeletedEqualTo(false);
        ca.andCreatorIdEqualTo(String.valueOf(id));
        int num = (int) projectMapper.countByExample(projectExample);
        if (num > 0) {
            return new BaseResult(false, "该账号关联项目数据，不能删除～");
        }
        //删除账户关联角色
        relationService.delSourceId(id,DataStatus.RELATION_TYPE_USER_ROLE.getVal());
        return new BaseResult(true, recordMapper.updateByPrimaryKeySelective(user));
    }

    @Override
    public User detail(int id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<UserVo> list(UserVo record) {
        return recordMapper.pageList(record);
    }

    @Override
    public List<UserVo> listByRelation(Relation record) {
        return recordMapper.listByRelation(record);
    }

    @Override
    public ListResult page(UserVo record) {
        List<UserVo> list = list(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult pageNoAdmin(UserVo record) {
        List<UserVo> list = list(record);
        List<UserVo> listWidthoutAdmin = new ArrayList<>();
        list.forEach(item -> {
            if (!item.getName().equals("admin"))
                listWidthoutAdmin.add(item);
        });
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult pageWidthDepName(UserVo record) {
        record.setCategoryType(DataStatus.CATEGORY_DATA_TYPE_DEP.getVal()); //部门类型
        List<UserVo> list = recordMapper.pageListWithDep(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    /**
     * record.name required 权限名称
     *
     * @param record
     * @return
     */
    @Override
    public ListResult listByPermission(CategoryVo record) {
        List<User> users = recordMapper.listByPermission(record);
        List<User> listWidthoutAdmin = new ArrayList<>();
        users.forEach(item -> {
            if (!item.getName().equals("admin"))
                listWidthoutAdmin.add(item);
        });
        return new ListResult(true, listWidthoutAdmin);
    }

    @Override
    public long count(UserVo record) {
        UserExample recordExample = new UserExample();
        UserExample.Criteria criteria = recordExample.createCriteria();
        criteria.andDeletedEqualTo(false);//未删除状态
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNameLike(record.getSearch());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        if (record.getDepId() != null) {
            criteria.andDepIdEqualTo(record.getDepId());
        }
        if (record.getBusId() != null) {
            criteria.andBusIdEqualTo(record.getBusId());
        }
        return recordMapper.countByExample(recordExample);
    }
}
